<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/18
 * Time: 14:47
 */

namespace Admin\Ims\Controllers;
use \Admin\Frontend\Controllers\ControllerBase;
use Admin\Models\coop\XhCoopInfo;
use Admin\Models\crm\XhcustInfo;
use Admin\Models\ims\XHImsApplyTablet;
use Admin\Models\ims\XHImsBrand;
use Admin\Models\ims\XHImsProduce;
use Admin\Models\ims\XHImsProduceIn;
use Admin\Models\ims\XHImsProduceOut;
use Admin\Models\ims\XHImsProduceType;
use Admin\Models\sys\XhsysEnum;
use Helpers\Assets;
use Helpers\Hrm;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\XhException;
use Modules\Ims;
use Modules\Power;
use Modules\School;

class DetailController extends ControllerBase
{


    public static $enum = [
        'iInType'  => [1 => '采购入库', 2 => '退还入库', 3 => '维修返还'],
        'iOutType' => [1 => '登记出库', 2 => '申领出库', 3 => '流程计划出库', 4 => '维修出库'],
        'iDevType' => [
            2 => '<div class="grid-cell-text-bg-green">学生机</div>',
            3 => '<div class="grid-cell-text-bg-blue">教师机</div>',
            4 => '<div class="grid-cell-text-bg-yellow">备用机</div>',
            5 => '<div class="grid-cell-text-bg-gray">公用机</div>',
            6 => '<div class="grid-cell-text-bg-red">自用机</div>'
        ]
    ];

    /**
     * 入库明细
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180718
     */
    public function inListAction()
    {
        Assets::easyUI();
        $type = $this->request->getQuery('type', 'string');
        $this->view->setTemplateBefore('listForm');
        $this->view->pick('detail/inList');
        Assets::importJs('js/detail/inList.js');
        Template::exists('Prod_In', 'list') or die(Main::showMessageModal('Prod_In配置文件不存在，请先创建！', 109106002));
        $listSearchArr1 = $listButtonArr = [];
        $listSearchArr1[] = array('type' => 'select',
            'id' => 'list_search_type', 'data' => ['' => '-入库类型-'] + self::$enum['iInType'], 'default' => '');
        $listSearchArr1[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr1[] = array('type' => 'button',
            'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        if (Power::exist('Ims_ResInList_Add')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '采购入库',
                'icon' => 'fa-plus');
            $listButtonArr[] = array('plain' => 'true', 'id' =>
                'bt_list_return', 'text' => '退还入库', 'icon' => 'fa-plus');
        }
        if (Power::exist('Ims_ResInList_Edit')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_edit', 'text' => '编辑',
                'icon' => 'fa-edit');
        }
        if (Power::exist('Ims_ResInList_Del')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除',
                'icon' => 'fa-trash');
        }
        if ($type && $type == 2) {
            $listSearchArr1 = $listButtonArr = [];
            $listSearchArr1[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
            $listSearchArr1[] = array('type' => 'button',
                'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        }

        return $this->view->setVars(array(
            'List' => Template::createList('list', 'Prod_In', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr1, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ])
        ));
    }

    /**
     * 采购表单
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180719
     */
    public function inFormAction()
    {
        $this->view->pick('detail/inForm');
        Assets::select2();
        Assets::importJs('js/detail/inForm.js');
        //合作伙伴信息
        $prods = XHImsProduce::find([
            'columns'    => 'iProdId,sProdName',
            'conditions' => 'bDelete = 0 and iProdAttr = 1',
        ])->toArray();
        return $this->view->setVars([
            'prods' => array_column($prods, 'sProdName', 'iProdId'),
            'coop' => XhCoopInfo::getSupply()
        ]);
    }

    /**
     * 归还表单
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180727
     */
    public function returnFormAction()
    {
        $this->view->pick('detail/returnForm');
        Assets::select2();
        Assets::importJs('js/detail/returnForm.js');
        //合作伙伴信息
        $prods = XHImsProduce::find([
            'columns'    => 'iProdId,sProdName',
            'conditions' => 'bDelete = 0 and iProdAttr = 1',
        ])->toArray();
        $schools = XhcustInfo::find([  //学校
            'columns' => 'iSchoolId,sSchoolName',
            'conditions' => 'bDelete=0 AND iSchoolId is not null'
        ]);
        $schools = array_column($schools->toArray(), 'sSchoolName', 'iSchoolId');
        return $this->view->setVars([
            'prods' => array_column($prods, 'sProdName', 'iProdId'),
            'schools' => $schools
        ]);
    }

    /**
     * 获取入库数据
     *
     * @param $showAll
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180718
     */
    public function getInAction($showAll = false)
    {
        try {
            $iProdId = $this->request->getPost('iProdId', 'int');
            $type    = $this->request->getPost('type', 'string');
            $key     = $this->request->getPost('key', 'string');
            $typeId  = $this->request->getPost('typeId', 'string');
            $builder = $this->modelsManager->createBuilder()
                ->columns('*')
                ->from('Admin\\Models\\ims\\XHImsProduceIn')
                ->where('bDelete = 0');

            if ($iProdId) {
                $builder->andWhere('iProdId = :iProdId:', ['iProdId' => $iProdId]);
            }
            if ($type) {
                $builder->andWhere('iInType = :iInType:', ['iInType' => $type]);
            }
            if ($typeId) {
                $builder->andWhere('iInTypeId = :iInTypeId:', ['iInTypeId' => $typeId]);
            }
            if ($key) {
                $prodId = Ims::searchProduce($key, false);
                $schoolId = School::searchSchool($key, false);
                $keyConditions = [
                    'conditions' => [],
                    'bind' => []
                ];
                if ($prodId) {
                    $keyConditions['conditions'][] = 'iProdId in ({prods:array}) ';
                    $keyConditions['bind'] = array_merge($keyConditions['bind'], ['prods' => $prodId]);
                }
                if ($schoolId) {
                    $keyConditions['conditions'][] = 'iSchoolId in ({schools:array}) ';
                    $keyConditions['bind'] = array_merge($keyConditions['bind'], ['schools' => $schoolId]);
                }
                if ($keyConditions['bind']) {
                    $builder->andWhere(implode(' or ', $keyConditions['conditions']), $keyConditions['bind']);
                }
            }
            if (!User::isAdmin() && !$showAll) { //不是超管
                $nowUserId = Main::getLoginUserInfo('userId');
                $depArr = User::getExtraPower('dep', 'resIn', $nowUserId);
                if ($depArr) { //有额外权限
                    $userIds = Hrm::getUserByDepId($depArr, true);
                    if ($userIds) {
                        $builder->andWhere(
                            'iCreateUserId in ({ids:array}) or iCreateUserId = :userId:',
                            ['ids' => $userIds, 'userId' => $nowUserId]
                        );
                    } else {
                        $builder->andWhere(' iCreateUserId = :userId:', ['userId' => $nowUserId]);
                    }
                } else {
                    $builder->andWhere(' iCreateUserId = :userId:', ['userId' => $nowUserId]);
                }
            }
            $builder->orderBy('tCreateDate desc');
            $data = Main::runBuilderPage($builder, [
                'iInType' => self::$enum['iInType'],
                'iProdId' => XHImsProduce::getProds(),
                'iCIId'   => [0 => ''] + XhCoopInfo::getSupply(),
                'tProdStart' => ['0000-00-00' => ''],
                'tProdEnd' => ['0000-00-00' => ''],
                'iInTime'  => ['0000-00-00' => ''],
                'iSchoolId' => School::getSchools(true) + [ 0 => ''],
                'iDevType'  => self::$enum['iDevType']
            ]);
            foreach ($data['rows'] as &$row) {
                $row['date'] = '';
                if ($row['tProdStart'] || $row['tProdEnd']) {
                    $row['date'] .= $row['tProdStart'] ?: '未知';
                    $row['date'] .= '~';
                    $row['date'] .= $row['tProdEnd'] ?: '未知';
                }
                switch ($row['iInType']) { //1 => '待确认' , 2 => '待领用', 3 => '已领用'
                    case '采购入库':
                        $row['iInType'] = '<div class="grid-cell-text-bg-gray">采购入库</div>';
                        break;
                    case '退还入库':
                        $row['iInType'] = '<div class="grid-cell-text-bg-blue">退还入库</div>';
                        break;
                    case '维修返还':
                        $row['iInType'] = '<div class="grid-cell-text-bg-green">维修返还</div>';
                        break;
                    default:
                        break;
                }
                $row['mDesc'] = '<div title="'.$row['mDesc'].'" style="text-overflow: ellipsis;white-space: nowrap;overflow: hidden;">'.$row['mDesc'].'</div>';
            }
            $sql = "select sum(iInNum) as total, sum(IFNULL(dInPrice, 0) * iInNum) as price from XHIms_ProduceIn where bDelete = 0";
            if ($iProdId) {
                $sql .= " and iProdId = {$iProdId} ";
            }
            $footerData = $this->db->fetchOne($sql);
            $data['footer'] = [[
                'iInNum'    => '总计：' . $footerData['total'],
                'iProdId' => '总采购价：' . $footerData['price'],
            ]];
            Main::runUserNameById(
                $data['rows'],
                ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId'],
                true
            );
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 保存入库
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180718
     */
    public function saveInAction()
    {
        try {
            $data = $this->request->getPost();
            if (!$data['iProdId'] || !$data['iInNum']) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            Ims::prodIn($data, [], $data['iInType'] == 1 ? '采购入库' : '退还入库');
            return $this->sendSuccessResponse('入库成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 删除入库数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180718
     */
    public function delInAction()
    {
        try {
            $this->db->begin();
            $ids = $this->request->getPost('ids', 'int');
            $objArr = XHImsProduceIn::find([
                'conditions' => 'bDelete = 0 and iPInId in ({ids:array})',
                'bind'       => ['ids' => $ids]
            ]);
            $nowUserId = Main::getLoginUserInfo('userId');
            $successStr = '删除成功';
            foreach ($objArr as $obj) {
                if (!User::isAdmin() && $nowUserId != $obj->iCreateUserId) {
                    $successStr .= ',已过滤无法删除的数据';
                    continue;
                }
                $obj->bDelete = 1;
                if (!$obj->save()) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '保存失败');
                }
                $prod = XHImsProduce::findFirst($obj->iProdId);
                $prod->iCurrentNum -= $obj->iInNum;
                if (!$prod->save()) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '保存失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse($successStr);
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 出库列表
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180719
     */
    public function outListAction()
    {
        Assets::easyUI('', true);
        $type = $this->request->getQuery('type', 'string');
        $this->view->setTemplateBefore('listForm');
        $this->view->pick('detail/outList');
        Assets::importJs('js/detail/outList.js');
        Template::exists('Prod_Out', 'list') or die(Main::showMessageModal('Prod_Out配置文件不存在，请先创建！', 109106002));
        $listSearchArr1 = $listButtonArr = [];
        $listSearchArr1[] = array('type' => 'select',
            'id' => 'list_search_type', 'data' => ['' => '-出库类型-'] + self::$enum['iOutType'], 'default' => '');
        $listSearchArr1[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr1[] = array('type' => 'button',
            'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        if (Power::exist('Ims_ResOutList_Add')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '登记出库', 'icon' => 'fa-plus');
        }
        if (Power::exist('Ims_ResOutList_Edit')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_edit', 'text' => '编辑', 'icon' => 'fa-edit');
        }
        if (Power::exist('Ims_ResOutList_Del')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        if ($type && $type == 2) {
            $listSearchArr1 = $listButtonArr = [];
            $listSearchArr1[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
            $listSearchArr1[] = array('type' => 'button',
                'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        }
        return $this->view->setVars(array(
            'List' => Template::createList('list', 'Prod_Out', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr1, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ])
        ));
    }

    /**
     * 出库表单
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180719
     */
    public function outFormAction()
    {
        $this->view->pick('detail/outForm');
        Assets::select2();
        Assets::importJs('js/detail/outForm.js');
        $schools = XhcustInfo::find([  //学校
            'columns' => 'iSchoolId,sSchoolName',
            'conditions' => 'bDelete=0 AND iSchoolId is not null'
        ]);
        $schools = array_column($schools->toArray(), 'sSchoolName', 'iSchoolId');
        return $this->view->setVars([
            'prods'   => XHImsProduce::getProds(),
            'schools' => $schools,
            'iChargeMode' => XhsysEnum::getEnumByNodeName('收费模式')
        ]);
    }


    /**
     * 获取出库数据
     *
     * @param $showAll
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180719
     */
    public function getOutAction($showAll = false)
    {
        try {
            $iProdId = $this->request->getPost('iProdId', 'int');
            $type = $this->request->getPost('type', 'string');
            $key  = $this->request->getPost('key', 'string');
            $typeId = $this->request->getPost('typeId', 'string');
            $builder = $this->modelsManager->createBuilder()
                ->columns('*')
                ->from('Admin\\Models\\ims\\XHImsProduceOut')
                ->where('bDelete = 0 ');
            if ($iProdId) {
                $builder->andWhere('iProdId = :iProdId:', ['iProdId' => $iProdId]);
            } else {
                $builder->andWhere(' iParentId = 0');
            }
            if ($type) {
                $builder->andWhere('iOutType = :iOutType:', ['iOutType' => $type]);
            }
            if ($typeId) {
                $builder->andWhere('iOutTypeId = :iOutTypeId:', ['iOutTypeId' => $typeId]);
            }
            if ($key) {
                $prodId = Ims::searchProduce(trim($key), false);
                $schoolId = School::searchSchool(trim($key), false);
                $keyConditions = [
                    'conditions' => [],
                    'bind' => []
                ];
                if ($prodId) {
                    $keyConditions['conditions'][] = 'iProdId in ({prods:array}) ';
                    $keyConditions['bind'] = array_merge($keyConditions['bind'], ['prods' => $prodId]);
                }
                if ($schoolId) {
                    $keyConditions['conditions'][] = 'iSchoolId in ({schools:array}) ';
                    $keyConditions['bind'] = array_merge($keyConditions['bind'], ['schools' => $schoolId]);
                }
                if ($keyConditions['bind']) {
                    $builder->andWhere(implode(' or ', $keyConditions['conditions']), $keyConditions['bind']);
                }
            }

            if (!User::isAdmin() && !$showAll) { //不是超管
                $nowUserId = Main::getLoginUserInfo('userId');
                $depArr = User::getExtraPower('dep', 'resOut', $nowUserId);
                if ($depArr) { //有额外权限
                    $userIds = Hrm::getUserByDepId($depArr, true);
                    if ($userIds) {
                        $builder->andWhere(
                            'iCreateUserId in ({ids:array}) or iCreateUserId = :userId:',
                            ['ids' => $userIds, 'userId' => $nowUserId]
                        );
                    } else {
                        $builder->andWhere(' iCreateUserId = :userId:', ['userId' => $nowUserId]);
                    }
                } else {
                    $builder->andWhere(' iCreateUserId = :userId:', ['userId' => $nowUserId]);
                }
            }
            $builder->orderBy('tCreateDate desc');
            $data = Main::runBuilderPage($builder, [
                'iOutType' => self::$enum['iOutType'],
                'iProdId' => XHImsProduce::getProds(),
                'tOutTime' => ['0000-00-00' => ''],
                'iChargeMode' => XhsysEnum::getEnumByNodeName('收费模式') + [ 0 => ''],
                'iSchoolId'   => School::getSchools(true) + [ 0 => ''],
                'iDevType'  => self::$enum['iDevType']
            ]);
            $ids = array_column($data['rows'], 'iPOutId');
            $children = $this->getOutParts($ids);
            foreach ($data['rows'] as &$row) {
                if (Tool::getValue($children, $row['iPOutId'], null)) {
                    $parts = $children[$row['iPOutId']];
                    $row['extra'] = '<table><tr><th style="text-align: center">部件名称</th><th style="text-align: center">出库数量</th></tr>';
                    foreach ($parts as $item) {
                        $row['extra'] .= '<tr><td style="width: 200px;">' . $item['iProdId'] . '</td><td style="width: 100px;text-align: right">' . $item['iOutNum'] . '</td></tr>';
                    }
                    $row['extra'] .='</table>';
                } else {
                    $row['extra'] = '';
                }
                switch ($row['iOutType']) { //1 => '待确认' , 2 => '待领用', 3 => '已领用'
                    case '登记出库':
                        $row['iOutType'] = '<div class="grid-cell-text-bg-gray">登记出库</div>';
                        break;
                    case '申领出库':
                        $row['iOutType'] = '<div class="grid-cell-text-bg-blue">申领出库</div>';
                        break;
                    case '流程计划出库':
                        $row['iOutType'] = '<div class="grid-cell-text-bg-green">流程计划出库</div>';
                        break;
                    case '维修出库':
                        $row['iOutType'] = '<div class="grid-cell-text-bg-yellow">维修出库</div>';
                        break;
                    default:
                        break;
                }
                $row['mDesc'] = '<div title="'.$row['mDesc'].'" style="text-overflow: ellipsis;white-space: nowrap;overflow: hidden;">'.$row['mDesc'].'</div>';
            }
            $sql = "select sum(iOutNum) as total, sum(IFNULL(dOutPrice, 0) * iOutNum) as price from XHIms_ProduceOut where bDelete = 0";
            if ($iProdId) {
                $sql .= " and iProdId = {$iProdId} ";
            }
            $footerData = $this->db->fetchOne($sql);
            $data['footer'] = [[
                'iOutNum'    => '总计：' . $footerData['total'],
                'iProdId' => '总销售价：' . $footerData['price']
            ]];
            Main::runUserNameById(
                $data['rows'],
                ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId'],
                true
            );
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 获取部件
     *
     * @param $ids
     *
     * @return array
     *
     * create by dale  20180720
     */
    private function getOutParts($ids){
        if (!$ids) {
            return [];
        }
        $parts = XHImsProduceOut::find([
            'conditions' => 'bDelete = 0 and  iParentId in ({ids:array})',
            'bind'       => ['ids' => $ids ]
        ])->toArray();
        if (!$parts) {
            return [];
        }
        Main::runUserNameById(
            $parts,
            ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId'],
            true
        );
        $returnArr = [];
        $prods = XHImsProduce::getProds();
        foreach ($parts as $part) {
            $part['iProdId'] = $prods[$part['iProdId']];
            $returnArr[$part['iParentId']][] = $part;
        }
        return $returnArr;
    }

    /**
     * 保存出库
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180719
     */
    public function saveOutAction()
    {
        try {
            $data = $this->request->getPost();
            if (!$data['iProdId'] || !$data['iOutNum']) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            Ims::prodOut($data, [], '登记出库');
            return $this->sendSuccessResponse('出库成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }


    /**
     * 删除出库
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180719
     */
    public function delOutAction()
    {
        try {
            $this->db->begin();
            $ids = $this->request->getPost('ids', 'int');
            $objArr = XHImsProduceOut::find([
                'conditions' => 'bDelete = 0 and iPOutId in ({ids:array}) and iParentId = 0',
                'bind'       => ['ids' => $ids]
            ]);
            $nowUserId = Main::getLoginUserInfo('userId');
            $successStr = '删除成功';
            foreach ($objArr as $obj) {
                if (!User::isAdmin() && $nowUserId != $obj->iCreateUserId) {
                    $successStr .= ',已过滤无法删除的数据';
                    continue;
                }
                $obj->bDelete = 1;
                if (!$obj->save()) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '保存失败');
                }
                $prod = XHImsProduce::findFirst($obj->iProdId);
                if ($prod->iProdAttr == 1) {
                    $prod->iCurrentNum += $obj->iOutNum;
                    if (!$prod->save()) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(500, '库存更新失败');
                    }
                } elseif ($prod->iProdAttr == 2) { //自定义商品,删除子商品
                    $parts = XHImsProduceOut::find([
                        'conditions' => 'bDelete = 0 and iParentId = :iParentId:',
                        'bind'       => ['iParentId' => $obj->iPOutId]
                    ]);
                    foreach ($parts as $part) {
                        $part->bDelete = 1 ;
                        if (!$part->save()) {
                            $this->db->rollback();
                            return $this->sendErrorResponse(500, '子商品删除失败');
                        }
                        $partProd = XHImsProduce::findFirst($part->iProdId);
                        $partProd->iCurrentNum += $part->iOutNum;
                        if (!$partProd->save()) {
                            $this->db->rollback();
                            return $this->sendErrorResponse(500, '子商品库存更新失败');
                        }
                    }
                } else {
                    return $this->sendErrorResponse(500, '商品属性不对应');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse($successStr);
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 库存列表
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180720
     */
    public function detailListAction(){
        Assets::easyUI();
        $this->view->setTemplateBefore('listForm');
        Assets::importJs('js/detail/detailList.js');
        Template::exists('detailList', 'list') or die(Main::showMessageModal('resList配置文件不存在，请先创建！', 109106002));
        $listSearchArr1 = $listButtonArr = [];
        $listSearchArr1[] = array('type' => 'select',
            'id' => 'prod_part', 'data' => ['' =>'—全部—', 1 => '非部件', 2 => '部件'], 'default' => '');
        $listSearchArr1[] = array('type' => 'select',
            'id' => 'prod_brand', 'data' => XHImsBrand::getBrandEnum() + ['' => '——品牌——'], 'default' => '');
        $listSearchArr1[] = array('type' => 'text',
            'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr1[] = array('type' => 'button',
            'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        return $this->view->setVars(array(
            'List' => Template::createList('list', 'detailList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr1, false),
//                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ])
        ));
    }

    /**
     * 获取库存管理
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180720
     */
    public function getDetailAction(){
        try {
            $part = $this->request->getPost('part', 'int');
            $brand = $this->request->getPost('brand', 'int');
            $key   = $this->request->getPost('key', 'string');
            $builder = $this->modelsManager->createBuilder()
                ->from('Admin\\Models\\ims\\XHImsProduce')
                ->where('bDelete = 0 and iProdAttr = 1');
            if ($part) {
                $builder->andWhere('bParts = :part:', ['part' => $part-1]);
            }
            if ($brand) {
                $builder->andWhere('iPBId = :iPBId:', ['iPBId' => $brand]);
            }
            if ($key) {
                $builder->andWhere('sProdName like :key:', ['key' => '%'.$key.'%']);
            }
            if (!User::isAdmin()) {
                $nowUserId = Main::getLoginUserInfo('userId');
                $depArr = User::getExtraPower('dep', 'prod', $nowUserId);
                if ($depArr) { //有额外权限
                    $userIds = Hrm::getUserByDepId($depArr, true);
                    if ($userIds) {
                        $builder->andWhere(
                            'iCreateUserId in ({ids:array}) or iCreateUserId = :userId:',
                            ['ids' => $userIds, 'userId' => $nowUserId]
                        );
                    } else {
                        $builder->andWhere(' iCreateUserId = :userId:', ['userId' => $nowUserId]);
                    }
                } else {
                    $builder->andWhere(' iCreateUserId = :userId:', ['userId' => $nowUserId]);
                }
            }
            $data = Main::runBuilderPage(
                $builder,
                [
                    'iPTId'     => XHImsProduceType::getProduceTypeEnum(),
                    'bParts'    => [1 => '是' , 0 => '否'],
                    'iPBId'     => XHImsBrand::getBrandEnum()
                ]
            );
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 出入库详情
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180720
     */
    public function inOutListAction()
    {
        $this->view->pick('detail/inOutList');
        Assets::easyUI();
        Assets::importJs('js/detail/inOutList.js');
        return $this->view->setVars(array(
            'resInList' => Template::createList('resInList', 'Prod_In', [
            ]),
            'resOutList' => Template::createList('resOutList', 'Prod_Out', [
            ]),
        ));
    }

    /**
     * 添加备注
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180724
     */
    public function saveDescAction()
    {
        try{
            $id = $this->request->getPost('id', 'string');
            $sRemark = $this->request->getPost('sRemark', 'string');
            $type = $this->request->getPost('type', 'string');
            if($type == 'in'){ //入库
                $obj = XHImsProduceIn::findFirst($id);
            }else{ //出库
                $obj = XHImsProduceOut::findFirst($id);
            }
            if (!$obj) {
                return $this->sendErrorResponse(400 ,'缺少参数');
            }
            if($obj->mDesc){
                $obj->mDesc = substr($obj->mDesc , -1) == ';' ? $obj->mDesc  . $sRemark : $obj->mDesc . ';' . $sRemark;
            }else{
                $obj->mDesc = $sRemark;
            }
            if(!$obj->save()){
                return $this->sendErrorResponse(500 ,'保存失败');
            }
           return $this->sendSuccessResponse('备注保存成功');
        }catch (\Exception $e){
            return $this->sendErrorResponse(500 , $e->getMessage());
        }
    }

    /**
     * 修改价格
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180724
     */
    public function modifyPriceAction(){
        try {
            $id    = $this->request->getPost('id'    , 'int');
            $price = $this->request->getPost('price' , 'string');
            $type  = $this->request->getPost('type'  , 'string');
            if (!$id  || !$price ) {
                return $this->sendErrorResponse(401 ,'缺少参数');
            }
            if ($type == 'in') {
                $obj = XHImsProduceIn::findFirst($id);
                $obj->dInPrice = $price;
            } else if ($type == 'out') {
               $obj = XHImsProduceOut::findFirst($id);
               $obj->dOutPrice = $price;
            } else {
                return $this->sendErrorResponse(500 , '未知类型');
            }
            if(!$obj->save()){
                return $this->sendErrorResponse(500 , '价格修改失败');
            }
            return $this->sendSuccessResponse('修改成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 修改信息界面
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180806
     */
    public function modifyFormAction()
    {
        $this->view->pick('detail/modifyForm');
        Assets::select2();
        Assets::importJs('js/detail/modifyForm.js');
        $devType = self::$enum['iDevType'];
        $devType = array_map(
            function ($val) {
                return strip_tags($val);
            },
            $devType
        );
        $schools = XhcustInfo::find([
            'columns'    => 'iSchoolId,sSchoolName',
            'conditions' => 'bDelete = 0  and iSchoolId is not null'
        ])->toArray();
        $schools = array_column($schools, 'sSchoolName', 'iSchoolId');
        $ids = $this->request->getQuery('ids', 'string');
        $ids = is_string($ids) ? explode(',', $ids) : $ids;
        $ids = array_values(array_filter($ids));
        $type = $this->request->getQuery('type', 'string');
        if (count($ids) == 1) {
            if ($type == 'in') {
                $info = XHImsProduceIn::findFirst([
                    'columns'    => 'iDevType as devType, dInPrice as price,
                    iSchoolId as schoolId,iProdId as prodId,iInNum as num',
                    'conditions' => 'bDelete = 0 and iPInId = :iPInId:',
                    'bind'       => ['iPInId' => $ids[0]],
                ])->toArray();
            } elseif ($type == 'out') {
                $info = XHImsProduceOut::findFirst([
                    'columns'    => 'iDevType as devType, dOutPrice as price,
                    iSchoolId as schoolId,iProdId as prodId,iOutNum as num',
                    'conditions' => 'bDelete = 0 and iPOutId = :iPOutId:',
                    'bind'       => ['iPOutId' => $ids[0]],
                ])->toArray();
//                $info = XHImsProduceOut::findFirst($ids[0])->toArray();
            } else {
                return $this->sendViewError('未知类型');
            }
            $this->view->setVar('info', $info);
        }
        return $this->view->setVars([
            'devType' => $devType,
            'schools' => $schools,
            'prods'   => XHImsProduce::getProds()
        ]);
    }

    /**
     * 修改出入库信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180806
     */
    public function modifyInfoAction()
    {
        try {
            $this->db->begin();
            $ids      = $this->request->getPost('ids', 'int');
            $schoolId = $this->request->getPost('schoolId', 'int');
            $devType  = $this->request->getPost('devType', 'int');
            $desc     = $this->request->getPost('desc', 'string');
            $price    = $this->request->getPost('price', 'string');
            $type     = $this->request->getPost('type', 'string'); //出库还是入库
            $num      = $this->request->getPost('num', 'int');
            $prodId   = $this->request->getPost('prodId', 'int');
            if (!$ids) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            if (count($ids) > 1 && ($num || $prodId)) {
                return $this->sendErrorResponse(400, '商品数量和商品类型不支持批量修改');
            }
            $tabletIdArr = Ims::getProdsByTypeName('平板', false, true);
            $needChange = [];
            if ($type == 'in') {
                $objArr = XHImsProduceIn::find([
                    'conditions' => 'bDelete = 0 and iPInId in ({ids:array})',
                    'bind'       => ['ids' => $ids]
                ]);
                foreach ($objArr as $obj) {
                    if (in_array($obj->iProdId, $tabletIdArr)) {
                        $obj->iDevType = $devType ?: $obj->iDevType;
                    }
                    $obj->iSchoolId = $schoolId ?: $obj->iSchoolId;
                    $obj->mDesc     = $desc ? $obj->mDesc . ';' . $desc : $obj->mDesc;
                    $obj->dInPrice  = $price ?: $obj->dInPrice;
                    if ($num && $num != $obj->iInNum) {
                        $obj->iInNum    = $num;
                        $needChange[] = $obj->iProdId;
                    }
                    if ($prodId && $prodId != $obj->iProdId) {
                        $needChange[] = $obj->iProdId;
                        $needChange[] = $prodId;
                        $obj->iProdId = $prodId;
                    }
                    if (!$obj->save()) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(500, '保存失败');
                    }
                    $needChange = array_values(array_filter(array_unique($needChange)));
                    foreach ($needChange as $prodId) {
                        Ims::uploadData($prodId);
                    }
                }

            } elseif ($type == 'out') {
                $objArr = XHImsProduceOut::find([
                    'conditions' => 'bDelete = 0 and iPOutId in ({ids:array})',
                    'bind'       => ['ids' => $ids]
                ]);
                foreach ($objArr as $obj) {
                    if (in_array($obj->iProdId, $tabletIdArr)) {
                        $obj->iDevType = $devType ?: $obj->iDevType;
                    }
                    $obj->iSchoolId = $schoolId ?: $obj->iSchoolId;
                    $obj->mDesc     = $desc ? $obj->mDesc . ';' . $desc : $obj->mDesc;
                    $obj->dOutPrice  = $price ?: $obj->dOutPrice;
                    $sourceProdId = $obj->iProdId; //原来的商品id
                    if ($num && $num != $obj->iOutNum) {
                        $obj->iOutNum    = $num;
                        $needChange[] = $obj->iProdId;
                    }
                    if ($prodId && $prodId != $obj->iProdId) { //出库改变商品类型的
                        $needChange[] = $obj->iProdId;
                        $needChange[] = $prodId;
                        $obj->iProdId = $prodId;

                        if ($obj->iOutType == 2  && $obj->iOutTypeId) {
                            $applyTab = XHImsApplyTablet::findFirst([
                                'conditions' => 'bDelete= 0 and iRTId = :iRTId:',
                                'bind'       => ['iRTId' => $obj->iOutTypeId]
                            ]);
                            if (!$applyTab) {
                                throw new XhException('该记录未关联设备申领记录');
                            }
                            if ($obj->iDevType == 2) { //学生机修改
                                $applyTab->iProdId = $prodId;
                                if (!$applyTab->save()) {
                                    throw new XhException('设备申领记录更新失败');
                                }
                            } else if ($obj->iDevType == 3) { //教师机修改
                                $tchBackInfo = $applyTab->mTchBackInfo;
                                if (is_string($tchBackInfo)) {
                                    $tchBackInfo = $tchBackInfo ? unserialize($tchBackInfo) : [];
                                }
                                if (!$tchBackInfo && $applyTab->iSignState == 0) { //没有教师日志信息
                                    $tchTabInfo = $applyTab->mTchCode;
                                    if (is_string($tchTabInfo)) {
                                        $tchTabInfo = $tchTabInfo ? unserialize($tchTabInfo) : [];
                                    }
                                    if (!$tchTabInfo) {
                                        throw new XhException('没有教师平板信息修改');
                                    }
                                    $check = array_values(array_filter(array_unique(array_column($tchTabInfo, 'iProdId'))));
                                    if (count($check) == 1) {
                                        if ($sourceProdId == $check[0] && count($tchTabInfo) == $obj->iOutNum) {
                                            $applyTab->mTchBackInfo = [
                                                0 => ['prodId' => $prodId, 'prodNum' => $obj->iOutNum]
                                            ];
                                            if (!$applyTab->save()) {
                                                throw new XhException('设备申领记录更新失败');
                                            }
                                        }
                                    } else {
                                        throw new XhException('异常数目无法更新申领记录');
                                    }

                                } else if ($tchBackInfo && count($tchBackInfo) == 1) { //同一种类型
                                    if ($sourceProdId = $tchBackInfo[0]['prodId']
                                        && $tchBackInfo[0]['prodNum'] == $obj->iOutNum) {
                                        $applyTab->mTchBackInfo = [
                                            0 => ['prodId' => $prodId, 'prodNum' => $obj->iOutNum]
                                        ];
                                        if (!$applyTab->save()) {
                                            throw new XhException('设备申领记录更新失败');
                                        }
                                    }
                                } else {
                                    throw new XhException('设备申领记录无法更新');
                                }
                            } else if (in_array($obj->iDevType, [4, 5, 6])) { //备用 公用 自用
                                $tchTabInfo = $applyTab->mTchCode;
                                if (is_string($tchTabInfo)) {
                                    $tchTabInfo = $tchTabInfo ? unserialize($tchTabInfo) : [];
                                }
                                if (!$tchTabInfo) {
                                    throw new XhException('没有平板信息');
                                }
                                $check = array_values(array_filter(array_unique(array_column($tchTabInfo, 'iProdId'))));
                                if (count($check) == 1) {
                                    if ($sourceProdId == $check[0] && count($tchTabInfo) == $obj->iOutNum) {
                                        $applyTab->mTchBackInfo = [
                                            0 => ['prodId' => $prodId, 'prodNum' => $obj->iOutNum]
                                        ];
                                        if (!$applyTab->save()) {
                                            throw new XhException('设备申领记录更新失败');
                                        }
                                    }
                                } else {
                                    throw new XhException('异常数目无法更新申领记录');
                                }
                            }
                        }

                    }
                    if (!$obj->save()) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(500, '保存失败');
                    }
                    $needChange = array_values(array_filter(array_unique($needChange)));
                    foreach ($needChange as $prodId) {
                        Ims::uploadData($prodId);
                    }
                }
            } else {
                return $this->sendErrorResponse(500, '类型不匹配');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('修改成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof \Helpers\XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

}